import 'dart:io';
import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:video_player/video_player.dart';

import '../../../common/index.dart';

class PublishBottomSheet extends ConsumerStatefulWidget {
  const PublishBottomSheet({super.key});

  @override
  ConsumerState<PublishBottomSheet> createState() => _PublishBottomSheetState();
}

class _PublishBottomSheetState extends ConsumerState<PublishBottomSheet> {
  final PageController _pageController = PageController();
  int _currentPage = 0;
  String? _selectedEmotion = 'happy';
  final TextEditingController _textController = TextEditingController();
  final TextEditingController _contentController = TextEditingController();
  String? _selectedImagePath;
  String? _selectedVideoPath;

  @override
  void dispose() {
    _pageController.dispose();
    _textController.dispose();
    _contentController.dispose();
    super.dispose();
  }

  void _nextPage() {
    if (_currentPage < 1) {
      // 验证是否选择了情绪
      if (_selectedEmotion == null) {
        _showValidationMessage('Please select your mood first');
        return;
      }

      _pageController.nextPage(
        duration: Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }

  Future<void> _createEvent() async {
    // 验证输入
    if (_selectedEmotion == null) {
      _showValidationMessage('Please select your mood');
      return;
    }

    if (_contentController.text.trim().isEmpty) {
      _showValidationMessage('Please add your notes');
      return;
    }

    // 验证是否选择了媒体
    if (_selectedImagePath == null && _selectedVideoPath == null) {
      _showValidationMessage('Please select a photo or video');
      return;
    }

    // 获取当前用户
    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null) {
      _showValidationMessage('Please login first');
      return;
    }

    try {
      // 创建分享对象
      final shareId = DateTime.now().millisecondsSinceEpoch.toString();
      final share = ShareEntity(
        id: shareId,
        description: _contentController.text.trim(),
        image: _selectedImagePath ?? '',
        emotion: _selectedEmotion!,
        date: DateTime.now().toIso8601String(),
        commentIds: [],
        browses: 0,
        video: _selectedVideoPath ?? '',
      );

      // 保存分享到数据库
      final shareSuccess = await ref
          .read(shareProvider.notifier)
          .createShare(share);

      if (shareSuccess) {
        // 将分享ID添加到用户的分享列表
        final userSuccess = await ref
            .read(userProvider.notifier)
            .updateShare(shareId);

        if (userSuccess) {
          // 显示成功弹窗
          if (mounted) {
            _showSuccessDialog();
          }
        } else {
          if (mounted) {
            _showValidationMessage('Failed to update user profile');
          }
        }
      } else {
        if (mounted) {
          _showValidationMessage('Failed to create share');
        }
      }
    } catch (e) {
      if (mounted) {
        _showValidationMessage('Error: $e');
      }
    }
  }

  // 显示媒体选择弹窗
  void _showMediaPickerDialog() {
    if (!mounted) return;

    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (context) => Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20.r),
            topRight: Radius.circular(20.r),
          ),
        ),
        child: SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 顶部拖拽指示器
              Container(
                margin: EdgeInsets.only(top: 12.h),
                width: 36.w,
                height: 4.h,
                decoration: BoxDecoration(
                  color: Color(0xFFE0E0E0),
                  borderRadius: BorderRadius.circular(2.r),
                ),
              ),

              SizedBox(height: 20.h),

              // 标题
              Text(
                'Select Media from Gallery',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF0F0E11),
                ),
              ),

              SizedBox(height: 30.h),

              // 选择按钮
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                child: Row(
                  children: [
                    // 图片选择按钮
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          Navigator.of(context).pop();
                          _pickImage();
                        },
                        child: Container(
                          height: 120.h,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(16.r),
                            border: Border.all(
                              color: Color(0xFFE0E0E0),
                              width: 1,
                            ),
                            boxShadow: [
                              BoxShadow(
                                color: Color(0x0A000000),
                                blurRadius: 8.r,
                                offset: Offset(0, 2.h),
                              ),
                            ],
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Container(
                                width: 48.w,
                                height: 48.w,
                                decoration: BoxDecoration(
                                  gradient: LinearGradient(
                                    begin: Alignment(0.00, 0.50),
                                    end: Alignment(1.00, 0.50),
                                    colors: [
                                      Color(0xFFFF8C00),
                                      Color(0xFFF8FFC7),
                                    ],
                                  ),
                                  borderRadius: BorderRadius.circular(24.r),
                                ),
                                child: Icon(
                                  Icons.photo_library_outlined,
                                  color: Colors.white,
                                  size: 24.w,
                                ),
                              ),
                              SizedBox(height: 12.h),
                              Text(
                                'Photo',
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.w500,
                                  color: Color(0xFF0F0E11),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),

                    SizedBox(width: 16.w),

                    // 视频选择按钮
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          Navigator.of(context).pop();
                          _pickVideo();
                        },
                        child: Container(
                          height: 120.h,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(16.r),
                            border: Border.all(
                              color: Color(0xFFE0E0E0),
                              width: 1,
                            ),
                            boxShadow: [
                              BoxShadow(
                                color: Color(0x0A000000),
                                blurRadius: 8.r,
                                offset: Offset(0, 2.h),
                              ),
                            ],
                          ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Container(
                                width: 48.w,
                                height: 48.w,
                                decoration: BoxDecoration(
                                  gradient: LinearGradient(
                                    begin: Alignment(0.00, 0.50),
                                    end: Alignment(1.00, 0.50),
                                    colors: [
                                      Color(0xFFFF8C00),
                                      Color(0xFFF8FFC7),
                                    ],
                                  ),
                                  borderRadius: BorderRadius.circular(24.r),
                                ),
                                child: Icon(
                                  Icons.video_library_outlined,
                                  color: Colors.white,
                                  size: 24.w,
                                ),
                              ),
                              SizedBox(height: 12.h),
                              Text(
                                'Video',
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.w500,
                                  color: Color(0xFF0F0E11),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              SizedBox(height: 30.h),

              // 取消按钮
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                child: GestureDetector(
                  onTap: () => Navigator.of(context).pop(),
                  child: Container(
                    width: double.infinity,
                    height: 48.h,
                    decoration: BoxDecoration(
                      color: Color(0xFFF5F5F5),
                      borderRadius: BorderRadius.circular(24.r),
                    ),
                    child: Center(
                      child: Text(
                        'Cancel',
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w500,
                          color: Color(0xFF666666),
                        ),
                      ),
                    ),
                  ),
                ),
              ),

              SizedBox(height: 20.h),
            ],
          ),
        ),
      ),
    );
  }

  // 选择图片
  Future<void> _pickImage() async {
    try {
      final String? imagePath = await ImagePickerUtil.pickImageFromGallery();
      if (imagePath != null && mounted) {
        setState(() {
          _selectedImagePath = imagePath;
          _selectedVideoPath = null; // 清除视频选择
        });
      }
    } catch (e) {
      if (mounted) {
        _showValidationMessage('Failed to select image: $e');
      }
    }
  }

  // 选择视频
  Future<void> _pickVideo() async {
    try {
      final String? videoPath = await VideoPickerUtil.pickVideoFromGallery();
      if (videoPath != null && mounted) {
        setState(() {
          _selectedVideoPath = videoPath;
          _selectedImagePath = null; // 清除图片选择
        });
      }
    } catch (e) {
      if (mounted) {
        _showValidationMessage('Failed to select video: $e');
      }
    }
  }

  // 构建媒体预览
  Widget? _buildMediaPreview() {
    if (_selectedImagePath != null) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(45.r), // 增大圆角
        child: Image.file(
          File(_selectedImagePath!),
          width: 125.w,
          height: 125.w,
          fit: BoxFit.cover,
        ),
      );
    } else if (_selectedVideoPath != null) {
      return VideoThumbnailPreview(
        videoPath: _selectedVideoPath!,
        width: 125.w,
        height: 125.w,
      );
    }
    return null;
  }

  // 显示验证错误消息
  void _showValidationMessage(String message) {
    if (!mounted) return;

    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (context) => Dialog(
        backgroundColor: Colors.transparent,
        child: _buildValidationMessagePopup(message, isError: true),
      ),
    );
  }

  // 显示成功弹窗
  void _showSuccessDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => Dialog(
        backgroundColor: Colors.transparent,
        child: _buildSuccessfulPopup(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusScope.of(context).unfocus(),
      child: Container(
        width: 375.w,
        height: 725.h,
        decoration: ShapeDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.publishBg),
            fit: BoxFit.cover,
          ),
          color: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.r),
              topRight: Radius.circular(20.r),
            ),
          ),
        ),
        child: Column(
          children: [
            // 顶部拖拽指示器
            Container(
              margin: EdgeInsets.only(top: 12.h),
              width: 36.w,
              height: 4.h,
              decoration: BoxDecoration(
                color: Color(0xFFE0E0E0),
                borderRadius: BorderRadius.circular(2.r),
              ),
            ),

            // 顶部导航栏（页面指示器和按钮）
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 3.h),
              child: Row(
                children: [
                  // 返回按钮（仅在第二页显示）
                  if (_currentPage == 1)
                    GestureDetector(
                      onTap: () {
                        _pageController.previousPage(
                          duration: Duration(milliseconds: 300),
                          curve: Curves.easeInOut,
                        );
                      },
                      child: Container(
                        padding: EdgeInsets.all(6.w),
                        width: 32.w,
                        height: 32.h,
                        decoration: BoxDecoration(
                          color: Color(0xFFF5F5F5),
                          shape: BoxShape.circle,
                        ),
                        child: SvgPicture.asset(
                          MyIcons.publishBack,
                          colorFilter: ColorFilter.mode(
                            Color(0xFF666666),
                            BlendMode.srcIn,
                          ),
                        ),
                      ),
                    )
                  else
                    SizedBox(width: 32.w),
                  Expanded(
                    child: Center(
                      child: Text(
                        '${_currentPage + 1}/2',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Color(0xFF666666),
                        ),
                      ),
                    ),
                  ),

                  // 关闭按钮
                  GestureDetector(
                    onTap: () => Navigator.of(context).pop(),
                    child: Container(
                      width: 32.w,
                      height: 32.h,
                      decoration: BoxDecoration(
                        color: Color(0xFFF5F5F5),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.close,
                        size: 18.w,
                        color: Color(0xFF666666),
                      ),
                    ),
                  ),
                ],
              ),
            ),

            // PageView内容
            Expanded(
              child: PageView(
                physics: NeverScrollableScrollPhysics(),
                controller: _pageController,
                onPageChanged: (index) {
                  setState(() {
                    _currentPage = index;
                  });
                },
                children: [
                  _buildEmotionSelectionPage(),
                  _buildContentCreationPage(),
                ],
              ),
            ),

            // 底部按钮
            GestureDetector(
              onTap: _currentPage == 0 ? _nextPage : _createEvent,
              child: Container(
                width: 348.w,
                height: 54.h,
                decoration: ShapeDecoration(
                  gradient: LinearGradient(
                    begin: Alignment(0.00, 0.50),
                    end: Alignment(1.00, 0.50),
                    colors: [const Color(0xFFFF8C00), const Color(0xFFF8FFC7)],
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(60.r),
                  ),
                ),
                child: Center(
                  child: Text(
                    _currentPage == 0 ? 'Next Step' : 'Create Event',
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),

            SizedBox(height: 25.h),
            GestureDetector(
              onTap: () {
                UrlUtils().openUrl(UrlUtils.EULA);
              },
              child: Text(
                'EULA',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 14,
                  fontFamily: 'inter',
                  fontWeight: FontWeight.w400,
                  decoration: TextDecoration.underline,
                  height: 0.86,
                ),
              ),
            ),
            SizedBox(height: 45.h),
          ],
        ),
      ),
    );
  }

  // 构建情绪选择页面
  Widget _buildEmotionSelectionPage() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Column(
        children: [
          SizedBox(height: 20.h),
          Text(
            'What’s your mood now?',
            style: TextStyle(
              color: const Color(0xFF0F0E11),
              fontSize: 24.sp,
              fontWeight: FontWeight.w600,
            ),
          ),
          SizedBox(height: 20.h),
          Text(
            'Select mood that reflects the most how you are feeling at this moment.',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: const Color(0xBC545454),
              fontSize: 14.sp,
              fontWeight: FontWeight.w400,
            ),
          ),
          SizedBox(height: 125.h),

          // 横向滑动情绪选择器
          _buildHorizontalEmotionSelector(),
        ],
      ),
    );
  }

  // 构建内容创建页面
  Widget _buildContentCreationPage() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: SingleChildScrollView(
        physics: ClampingScrollPhysics(),
        child: ConstrainedBox(
          constraints: BoxConstraints(
            minHeight:
                MediaQuery.of(context).size.height -
                MediaQuery.of(context).viewInsets.bottom -
                200.h,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: 20.h),
              Text(
                'What’s reason making you feel this way?',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: const Color(0xFF0F0E11),
                  fontSize: 24.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
              SizedBox(height: 10.h),

              // 媒体选择按钮
              Center(
                child: GestureDetector(
                  onTap: _showMediaPickerDialog,
                  child: Container(
                    width: 125.w,
                    height: 125.w,
                    decoration: BoxDecoration(
                      image: _buildMediaPreview() == null
                          ? DecorationImage(
                              image: AssetImage(MyImages.publish),
                              fit: BoxFit.contain,
                            )
                          : null,
                    ),
                    child:
                        _buildMediaPreview() ??
                        Center(
                          child: SvgPicture.asset(
                            MyIcons.camera,
                            width: 32.w,
                            height: 32.w,
                          ),
                        ),
                  ),
                ),
              ),
              SizedBox(height: 10.h),

              // 情绪输入框
              Container(
                width: 351.w,
                height: 42.h,
                padding: EdgeInsets.only(left: 26.w),
                decoration: ShapeDecoration(
                  color: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.r),
                  ),
                ),
                child: Center(
                  child: TextField(
                    controller: _textController,
                    textInputAction: TextInputAction.next,
                    maxLines: null,
                    expands: true,
                    decoration: InputDecoration(
                      hintText: 'felt Disappointed, ConfusedBecause of Work',
                      hintStyle: TextStyle(
                        color: Color(0xFF999999),
                        fontSize: 12.sp,
                      ),
                      border: InputBorder.none,
                    ),
                  ),
                ),
              ),

              SizedBox(height: 25.h),
              SizedBox(
                width: 338.w,
                child: Text(
                  'Add your notes on any thought that reflating your mood',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: const Color(0xBC545454),
                    fontSize: 14.sp,
                    fontFamily: 'PingFang SC',
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
              SizedBox(height: 10.h),

              //内容输入
              Container(
                width: 351.w,
                height: 141.h,
                decoration: ShapeDecoration(
                  color: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.r),
                  ),
                ),
                padding: EdgeInsets.only(left: 10.w),
                child: TextField(
                  controller: _contentController,
                  textInputAction: TextInputAction.done,
                  maxLines: null,
                  expands: true,
                  decoration: InputDecoration(
                    hintText:
                        'How wonderful it is to be with yourself sometimes! I spent a wonderful day taking care of myself.',
                    hintStyle: TextStyle(
                      color: Color(0x4D0F0E11),
                      fontSize: 14.sp,
                      fontFamily: 'PingFang SC',
                      fontWeight: FontWeight.w400,
                    ),
                    border: InputBorder.none,
                  ),
                ),
              ),

              // 添加额外的底部空间，确保键盘弹起时有足够的滚动空间
              SizedBox(height: MediaQuery.of(context).viewInsets.bottom + 50.h),
            ],
          ),
        ),
      ),
    );
  }

  // 构建横向情绪选择器
  Widget _buildHorizontalEmotionSelector() {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: 98.h,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(MyImages.emotionSelectBg),
          fit: BoxFit.cover,
        ),
        borderRadius: BorderRadius.circular(20.r),
      ),
      child: PageView.builder(
        controller: PageController(viewportFraction: 0.2.w),
        onPageChanged: (index) {
          setState(() {
            _selectedEmotion = emotions[index].name;
          });
        },
        itemCount: emotions.length,
        itemBuilder: (context, index) {
          final emotion = emotions[index];
          final isSelected = _selectedEmotion == emotion.name;

          return GestureDetector(
            onTap: () {
              setState(() {
                _selectedEmotion = emotion.name;
              });
            },
            child: Container(
              margin: EdgeInsets.all(2.w),
              child: AnimatedContainer(
                duration: Duration(milliseconds: 300),
                curve: Curves.easeInOut,
                width: 60.w,
                height: 60.w,
                decoration: BoxDecoration(
                  image: isSelected
                      ? DecorationImage(
                          image: AssetImage(MyImages.emotionPublishBg),
                          fit: BoxFit.contain,
                        )
                      : null,
                  borderRadius: BorderRadius.circular(30.r),
                ),
                child: Center(
                  child: SizedBox(
                    width: 50.w,
                    height: 50.h,
                    child: Image.asset(emotion.image, fit: BoxFit.contain),
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  // 发布成功弹窗
  Widget _buildSuccessfulPopup() {
    return Container(
      width: 323.w,
      height: 425.h,
      decoration: ShapeDecoration(
        color: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20.r),
        ),
      ),
      child: Column(
        children: [
          Image.asset(MyImages.publishSuccessful, width: 171.w, height: 171.w),
          SizedBox(
            width: 268.w,
            child: Text.rich(
              TextSpan(
                children: [
                  TextSpan(
                    text: 'You’re on a ',
                    style: TextStyle(
                      color: const Color(0xFF100F11),
                      fontSize: 20.sp,
                      fontFamily: 'PingFang SC',
                      fontWeight: FontWeight.w600,
                      height: 1.35,
                      letterSpacing: 0.20,
                    ),
                  ),
                  TextSpan(
                    text: 'good way! ',
                    style: TextStyle(
                      color: const Color(0xFFFF8C00),
                      fontSize: 20.sp,
                      fontFamily: 'PingFang SC',
                      fontWeight: FontWeight.w600,
                      height: 1.35,
                      letterSpacing: 0.20,
                    ),
                  ),
                  TextSpan(
                    text: 'Your day is going ',
                    style: TextStyle(
                      color: const Color(0xFF100F11),
                      fontSize: 20.sp,
                      fontFamily: 'PingFang SC',
                      fontWeight: FontWeight.w600,
                      height: 1.35,
                      letterSpacing: 0.20,
                    ),
                  ),
                  TextSpan(
                    text: 'amazing',
                    style: TextStyle(
                      color: const Color(0xFFFF8C00),
                      fontSize: 20.sp,
                      fontFamily: 'PingFang SC',
                      fontWeight: FontWeight.w600,
                      height: 1.35,
                      letterSpacing: 0.20,
                    ),
                  ),
                ],
              ),
              textAlign: TextAlign.center,
            ),
          ),

          SizedBox(
            width: 275.w,
            child: Text(
              'Keep tracking your mood to know how to improve your mental health.',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: const Color(0xA5160B29),
                fontSize: 12.sp,
                fontFamily: 'PingFang SC',
                fontWeight: FontWeight.w400,
                height: 1.67,
              ),
            ),
          ),

          SizedBox(height: 25.h),

          GestureDetector(
            onTap: () {
              // 关闭成功弹窗
              Navigator.of(context).pop();

              Navigator.of(context).pop();
            },
            child: Container(
              width: 275.w,
              height: 51.h,
              decoration: ShapeDecoration(
                gradient: LinearGradient(
                  begin: Alignment(0.00, 0.50),
                  end: Alignment(1.00, 0.50),
                  colors: [const Color(0xFFFF8C00), const Color(0xFFF8FFC7)],
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30),
                ),
                shadows: [
                  BoxShadow(
                    color: Color(0x190D0A14),
                    blurRadius: 14.r,
                    offset: Offset(0, 8.h),
                    spreadRadius: 0,
                  ),
                ],
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                spacing: 10,
                children: [
                  Text(
                    'Got it',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 18.sp,
                      fontFamily: 'Pangram',
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建验证消息弹窗
  Widget _buildValidationMessagePopup(String message, {required bool isError}) {
    return Container(
      width: 300.w,
      padding: EdgeInsets.all(20.w),
      decoration: ShapeDecoration(
        color: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        shadows: [
          BoxShadow(
            color: Color(0x1A000000),
            blurRadius: 20.r,
            offset: Offset(0, 8.h),
            spreadRadius: 0,
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 图标
          Container(
            width: 48.w,
            height: 48.w,
            decoration: BoxDecoration(
              color: isError
                  ? Colors.red.withValues(alpha: 0.1)
                  : Colors.green.withValues(alpha: 0.1),
              shape: BoxShape.circle,
            ),
            child: Icon(
              isError ? Icons.error_outline : Icons.check_circle_outline,
              color: isError ? Colors.red : Colors.green,
              size: 24.w,
            ),
          ),

          SizedBox(height: 16.h),

          // 消息文本
          Text(
            message,
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Color(0xFF0F0E11),
              fontSize: 16.sp,
              fontWeight: FontWeight.w500,
            ),
          ),

          SizedBox(height: 20.h),

          // 确定按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              width: double.infinity,
              height: 44.h,
              decoration: ShapeDecoration(
                gradient: LinearGradient(
                  begin: Alignment(0.00, 0.50),
                  end: Alignment(1.00, 0.50),
                  colors: [Color(0xFFFF8C00), Color(0xFFF8FFC7)],
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(22.r),
                ),
              ),
              child: Center(
                child: Text(
                  'OK',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class VideoThumbnailPreview extends StatefulWidget {
  final String videoPath;
  final double width;
  final double height;

  const VideoThumbnailPreview({
    super.key,
    required this.videoPath,
    required this.width,
    required this.height,
  });

  @override
  State<VideoThumbnailPreview> createState() => _VideoThumbnailPreviewState();
}

class _VideoThumbnailPreviewState extends State<VideoThumbnailPreview> {
  VideoPlayerController? _controller;
  bool _isLoading = true;
  bool _hasError = false;

  @override
  void initState() {
    super.initState();
    _loadVideoThumbnail();
  }

  @override
  void dispose() {
    // 注意：不要释放控制器，因为它由缓存管理器管理
    super.dispose();
  }

  Future<void> _loadVideoThumbnail() async {
    try {
      // 使用缓存管理器获取或创建控制器
      final controller = await VideoThumbnailCache().getOrCreateController(
        widget.videoPath,
        useSmartThumbnail: true,
      );

      if (controller != null && mounted) {
        setState(() {
          _controller = controller;
          _isLoading = false;
        });
      } else if (mounted) {
        setState(() {
          _hasError = true;
          _isLoading = false;
        });
      }
    } catch (e) {
      debugPrint('加载视频缩略图失败: $e');
      if (mounted) {
        setState(() {
          _hasError = true;
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      height: widget.height,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(45.r),
        color: Colors.black.withValues(alpha: 0.1),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(45.r),
        child: Stack(
          alignment: Alignment.center,
          children: [
            // 视频缩略图或回退显示
            if (_controller != null && !_hasError)
              SizedBox(
                width: widget.width,
                height: widget.height,
                child: FittedBox(
                  fit: BoxFit.cover,
                  child: SizedBox(
                    width: _controller!.value.size.width,
                    height: _controller!.value.size.height,
                    child: VideoPlayer(_controller!),
                  ),
                ),
              )
            else
              Container(
                width: widget.width,
                height: widget.height,
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(45.r),
                ),
                child: Icon(
                  Icons.video_library,
                  color: Colors.grey[600],
                  size: 40.w,
                ),
              ),

            // 加载指示器
            if (_isLoading)
              Container(
                width: widget.width,
                height: widget.height,
                decoration: BoxDecoration(
                  color: Colors.black.withValues(alpha: 0.3),
                  borderRadius: BorderRadius.circular(45.r),
                ),
                child: Center(
                  child: SizedBox(
                    width: 24.w,
                    height: 24.w,
                    child: const CircularProgressIndicator(
                      color: Colors.white,
                      strokeWidth: 2,
                    ),
                  ),
                ),
              ),

            // 播放按钮覆盖层
            if (!_isLoading)
              Container(
                width: 32.w,
                height: 32.w,
                decoration: BoxDecoration(
                  color: Colors.white.withValues(alpha: 0.9),
                  shape: BoxShape.circle,
                ),
                child: Icon(Icons.play_arrow, color: Colors.black, size: 20.w),
              ),
          ],
        ),
      ),
    );
  }
}
